package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;

import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 分页查询功能
     *
     * @param page
     * @param pageSize
     * @param number
     * @return
     */
    @GetMapping("/page")
    //                      页数       页数总数       订单id
    public R<Page> page(int page, int pageSize, Long number, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime beginTime, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        //分页构造器对象
        //获取实体类 订单实体类
        Page<Orders> pageInfo = new Page<>(page, pageSize);//pageInfo  （包含条数，总条数 ,名称）

        //sql 实现器 实现订单类
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据name进行like模糊查询
        //订单id不能为空  通过订单id 模糊查询  返回订单id
        //SELECT * FROM orders NAME LIKE 'oderid';
        queryWrapper.like(number != null, Orders::getId, number);
        if (beginTime != null && endTime != null) {
            queryWrapper.ge(Orders::getOrderTime, beginTime).le(Orders::getOrderTime, endTime);
        }
        //添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //查询页数 总条数 返回查出的对象数据   放到条数框架中
        orderService.page(pageInfo, queryWrapper);

        //响应前端 pageInfo（包含条数总条数 和 对象数据）
        return R.success(pageInfo);
    }

    /**
     * 查询历史订单
     *
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize) {

        Page<Orders> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //             通过订单用户id 查询到当前用户id  返回当前用户id 订单信息
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        //按照降序排序
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //查询页数 总条数 返回查出的对象数据   放到条数框架中
        orderService.page(pageInfo, queryWrapper);

        Page<OrdersDto> ordersDtoPage = new Page<>();

        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");
        List<Orders> records = pageInfo.getRecords();

        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, item.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(lambdaQueryWrapper);
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            ordersDto.setOrderDetails(orderDetailList);

            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);
        //响应前端 pageInfo（包含条数总条数 和 对象数据）
        return R.success(ordersDtoPage);

    }

    @PutMapping
    public R<String> status(@RequestBody Orders orders) {

        orderService.updateById(orders);

        return R.success("更新成功");
    }
}